package com.gxa.wmcrm.util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class DBUtil {
    private static Properties properties = new Properties();

    // 在JdbcUtil的字节码被加载进JVM是执行，只执行一次
    static {
        try {
            // 通过输入流读取配置文件信息
            InputStream inStream = Thread.currentThread().
                    getContextClassLoader().getResourceAsStream("db.properties");
            properties.load(inStream);
            // 通过反射，注册JDBC驱动
            Class.forName(properties.getProperty("driverClassName"));
        } catch (IOException e) {
            System.out.println("读取properties文件失败！");
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            System.out.println("加载驱动失败！");
            e.printStackTrace();
        }
    }

    public static Connection getConn() {
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(
                    properties.getProperty("url"),
                    properties.getProperty("userName"),
                    properties.getProperty("password"));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    public static void closeConn(Connection conn, PreparedStatement ps,
                                 ResultSet rs) {

        try {
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {

            e.printStackTrace();
        }

        try {
            if (ps != null) {
                ps.close();
            }
        } catch (SQLException e) {

            e.printStackTrace();
        }

        try {
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException e) {

            e.printStackTrace();
        }

    }

}


